<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\api\common\Program;
use think\Config;
use think\Db;
use think\Validate;

use app\common\model\Typeone;
use app\common\model\Typetwo;
use app\common\model\Goods as GoodsModel;
use app\common\model\Collect as CollectModel;

/**
 * 产品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 获取分类列表
     */
    public function getTypeList()
    {
        $data = Typeone::field("id, name, image")->where("status", "=", "1")->order("weigh desc")->select();
        // 循环查询结果
        foreach ($data as $key => &$value) {
            // 查询每个学科的下级分类
            $value["child"] = Typetwo::field("id, p_id, name, image")->where("p_id", "=", $value["id"])->where("status", "=", "1")->order("weigh desc")->select();
        }

        $this->success('请求成功', $data);
    }

    /**
     * 获取产品列表
     */
    public function getGoodsList()
    {
        // 接收参数
        $one_id = $this->request->post("one_id/d", 0);
        $two_id = $this->request->post("two_id/d", 0);
        $brand_id = $this->request->post("brand_id/d", 0);
        $keyword = $this->request->post("keyword/s", "");
        $page = $this->request->post("page/d", 1);

        $where = [
            "status" => "1",
        ];
        if (!empty($one_id)) {
            $where["one_id"] = $one_id;
        }
        if (!empty($two_id)) {
            $where["two_id"] = $two_id;
        }
        if (!empty($brand_id)) {
            $where["brand_id"] = $brand_id;
        }
        if (!empty($keyword)) {
            $where["name"] = ["like", "%" . $keyword . "%"];
        }

        // 查询总条数
        $count = GoodsModel::where($where)->count();

        // 分页
        $limit = 20;

        $start = ($page - 1) * $limit;

        $total = ceil($count / $limit);

        $list = GoodsModel::field("id, one_id, two_id, goods_image, name, brand_id")->where($where)->order("weigh desc")->limit($start, $limit)->select();

        $data = [
            'total' => $total,
            'list' => $list,
        ];

        $this->success('请求成功', $data);
    }

    /**
     * 获取产品详情
     */
    public function getGoodsDetail()
    {
        $id = $this->request->post("id/d", 0);

        $data = GoodsModel::alias('gds')  // 使用别名
            ->join('brand b', 'b.id = gds.brand_id', 'left')  // 假设 brand_id 是外键
            ->where('gds.id', '=', $id)  // 明确使用 gds.id
            ->field('gds.*, b.name as brand_name')  // 明确指定字段
            ->find();
        $data['content'] = getHandleRichtext($data['content']);
        $this->success('请求成功', $data);
    }
    /**
     * 收藏商品
     */
    public function addCollect()
    {
        // 查用户ID
        $user_id = $this->auth->id;
        if (!$user_id) {
            return $this->error('请先登录');
        }
        // 接收参数
        $id = $this->request->post("id/d", 0);

        // 判断商品是否已经被收藏
        $existingCollect = CollectModel::where('user_id', $user_id)->where('goods_id', $id)->find();

        if ($existingCollect) {
            // 删除收藏记录
            $result = CollectModel::where('user_id', $user_id)->where('goods_id', $id)->delete();
            if ($result) {
                return $this->success('取消收藏成功');
            } else {
                return $this->error('取消收藏失败');
            }
        }

        // 组合数据
        $saveData = [
            "user_id" => $user_id,
            "goods_id" => $id,
            "createtime" => time(),
            "updatetime" => time(),
        ];

        $result = CollectModel::insert($saveData);

        if ($result) {
            return $this->success('收藏成功');
        } else {
            return $this->error('收藏失败');
        }
    }

    /**
     * 收藏列表
     */
    public function getCollectList()
    {
        // 查用户ID
        $user_id = $this->auth->id;
        $page = $this->request->post("page/d", 1);

        // 联表查询总条数
        $count_list = CollectModel::alias("col")
            ->join("goods gds", "gds.id = col.goods_id", "left")
            ->field("col.id, gds.id as goods_id, gds.goods_image, gds.name")
            ->where('user_id', $user_id)
            ->select();
        $count = count($count_list);

        // 分页
        $limit = 20;

        $start = ($page - 1) * $limit;

        $total = ceil($count / $limit);

        // 联表查询
        $list = CollectModel::alias("col")
            ->join("goods gds", "gds.id = col.goods_id and gds.status = 1", "left")
            ->field("col.id, gds.id as goods_id, gds.goods_image, gds.name")
            ->where('user_id', $user_id)
            ->limit($start, $limit)
            ->select();

        // 循环查询结果
        foreach ($list as $key => &$value) {
            // 拼接域名
            $value["goods_image"] = cdnurl($value["goods_image"], true);
        }

        $data = [
            'total' => $total,
            'list' => $list
        ];

        $this->success('请求成功', $data);
    }
    /**
     * 用户收藏状态
     */
    public function getCollectStatus()
    {
        $user_id = $this->auth->id;
        $goods_id = $this->request->post("goods_id/d", 0);

        $collect = CollectModel::where('user_id', $user_id)->where('goods_id', $goods_id)->find();

        if ($collect) {
            $this->success('已收藏', ['isCollection' => true]);
        } else {
            $this->success('未收藏', ['isCollection' => false]);
        }
    }
}
